/* ******************************************************************************
 * Launcher.java
 * 创建日期:2017年12月28日
 * Copyright 2017 kingter company, Inc. All rights reserved.
 * xxxx PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *******************************************************************************/
package com.ball.tools;

import java.awt.AWTException;
import java.awt.Desktop;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * <p>标题: Launcher</p>
 * <p>版权: Copyright (c) 2017</p>
 * <p>公司: xxxx</p>
 * <p>描述: 启动器</p>
 * 
 * @version 1.0
 * @author xieyicai
 */
public class Launcher {
	/** 日志记录器 */
	public static final Logger LOG = LoggerFactory.getLogger(Launcher.class);
	/** 判断程序是否运行在Windows上面 */
	public static final boolean IS_WINDOWS = System.getProperty("os.name").contains("Windows");
	/** 调试标识 */
	public static int DEBUG = "xieyicai".equals(System.getProperty("user.name")) ? 1 : 0;
	/**
	 * 
	 */
	public Launcher() {
	}

	private static boolean isRunning(int port){
		boolean started=false;
		java.net.Socket s=null;
		try{
			s=new java.net.Socket("127.0.0.1", port);
			started=true;
		}catch(Exception ex){
			started=false;
		}finally{
			if(s!=null){
				try {
					s.close();
				} catch (IOException e) {
					started=false;
				}
			}
		}
		return started;
	}
	public static URI getURI(int port) throws URISyntaxException{
		return new URI("http://localhost"+(port==80?"/":("/"+port+"/")));
	}
	public static void openBrowser(int port) throws IOException, URISyntaxException{
		if (Desktop.isDesktopSupported()) {
			Desktop.getDesktop().browse(getURI(port));
		} else {
			LOG.error("操作系统不支持。");
		}
	}
	public static void startServer(int port) throws URISyntaxException, AWTException, IOException{
		new MyNanolets(port).start();
		if (SystemTray.isSupported()){
			String filename="favicon.png";
			URL url=Launcher.class.getResource("/"+filename);
			if(url==null) url=new File(filename).toURI().toURL();
			Image image = Toolkit.getDefaultToolkit().getImage(url);
			//Image image = Toolkit.getDefaultToolkit().getImage("TrayIcon.png");
			MyActionListener listener=new MyActionListener(getURI(port));
			//初始化系统托盘图标
			PopupMenu popupTi = new PopupMenu();//弹出菜单
			MenuItem showItem = new MenuItem("show");//菜单项
			showItem.setActionCommand("show");
			showItem.addActionListener(listener);
			popupTi.add(showItem);
			MenuItem exitItem = new MenuItem("exit");
			exitItem.setActionCommand("exit");
			exitItem.addActionListener(listener);
			popupTi.add(exitItem);
			TrayIcon ti = new TrayIcon(image, "双色球缩水工具", popupTi);//图标，标题，右键弹出菜单
			ti.setActionCommand("show");
			ti.addActionListener(listener);//增加一个双击事件监听器
			SystemTray.getSystemTray().add(ti);
		}
	}
	public static class MyActionListener implements ActionListener{
		private URI uri;
		public MyActionListener(URI uri){
			setUri(uri);
		}
		public URI getUri() {
			return uri;
		}
		public void setUri(URI uri) {
			this.uri = uri;
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			try{
				if("show".equals(e.getActionCommand())){
					Desktop.getDesktop().browse(uri);
				}else if("exit".equals(e.getActionCommand())){
					System.exit(0);
				} else {
					LOG.error("无法响应事件。"+e.getSource());
				}
			}catch(Exception ex){
				LOG.error("错误", ex);
			}
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		long begin=System.currentTimeMillis();
		try{
			int port=80;
			for(int k=args.length-2; k>-1; k--){
				if("-port".equalsIgnoreCase(args[k])){
					try{
						port = Integer.parseInt(args[k+1]);
					}catch(Exception ex){
						System.err.println("端口号必须是一个整数。");
						return;
					}
				}
			}
			if(!isRunning(port)){
				startServer(port);
			}
			openBrowser(port);
		}catch(Exception e){
			e.printStackTrace();
		}
		System.out.println("\r\n主线程结束，耗时:"+(System.currentTimeMillis()-begin)+" 毫秒。");
	}
}
